#!/usr/bin/env bash

. $(dirname $0)/util
set -eu

TAG=${TAG:-test} buildxCmd bake $setFlags --load mainline

set -o pipefail -x
docker run --rm --privileged tonistiigi/binfmt:${TAG:-test} --uninstall qemu-*
status=$(docker run --rm --privileged tonistiigi/binfmt:${TAG:-test} --install all)

echo $status | jq .supported | grep linux/arm64
echo $status | jq .supported | grep linux/amd64
echo $status | jq .supported | grep linux/arm/v7
echo $status | jq .supported | grep linux/arm/v6
echo $status | jq .supported | grep linux/riscv64
echo $status | jq .supported | grep linux/ppc64le
echo $status | jq .supported | grep linux/386

echo $status | jq .emulators | grep qemu-riscv64
echo $status | jq .emulators | grep qemu-arm

docker run --rm --platform linux/arm64 alpine uname -a
docker run --rm --platform linux/arm/v7 alpine uname -a
docker run --rm --platform linux/ppc64le alpine uname -a
docker run --rm --platform linux/s390x alpine uname -a
docker run --rm --platform linux/386 alpine uname -a
docker run --rm --platform linux/riscv64 alpine uname -a

if [ "$(uname -m)" != "x86_64" ]; then exit 0; fi

status=$(docker run --rm --privileged tonistiigi/binfmt:${TAG:-test} --uninstall aarch64,riscv64)

if echo $status | jq .supported | grep linux/arm64; then exit 1; fi
if echo $status | jq .supported | grep linux/riscv64; then exit 1; fi
echo $status | jq .supported | grep linux/ppc64le
echo $status | jq .supported | grep linux/arm/v7

echo $status | jq .emulators | grep qemu-arm
echo $status | jq .emulators | grep qemu-ppc64le
if echo $status | jq .emulators | grep aarch64; then exit 1; fi
if echo $status | jq .emulators | grep riscv64; then exit 1; fi

if docker run --rm --platform linux/arm64 alpine uname -a 2>/dev/null; then exit 1; fi

docker run --rm --privileged tonistiigi/binfmt:${TAG:-test} --install arm64
docker run --rm --platform linux/arm64 alpine uname -a

docker run --rm --privileged tonistiigi/binfmt:${TAG:-test} --install riscv64
